<template>
  <div>
    <input type="file" @change="handleFileChange" accept="image/*" />
    <div class="cropper-container" style="display:none ">
      <img ref="imageRef" src=""  >
    </div>
    <button @click="cropImage" :disabled="!cropper">裁切并下载</button>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

const imageRef = ref(null)
const cropper = ref(null)

const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (!file || !file.type.startsWith('image/')) return

  const reader = new FileReader()
  reader.onload = (event) => {
    // 清理之前的Cropper实例
    destroyCropper()

    // 设置图片源
    imageRef.value.src = event.target.result

    // 初始化Cropper
    initCropper()
  }
  reader.onerror = () => console.error('文件读取失败')
  reader.readAsDataURL(file)
}

const initCropper = () => {
  cropper.value = new Cropper(imageRef.value, {
    viewMode: 0,
    dragMode: 'none',
    autoCrop:true,
    modal:true,
    preview: '.before',
    background: true,
    autoCropArea: 1,
    zoomOnWheel: false,
    minContainerWidth:116,
    minContainerHeight:98,
    minCanvasWidth:116,
    minCanvasHeight:98,
    minCropBoxWidth: 116,
    minCropBoxHeight: 98,
    // ready: function() {
    //   // 初始化后立即设置裁剪框大小为100x100
    //   this.cropper.setCropBoxData({
    //     left: 0,
    //     top: 0,
    //     width: 116,
    //     height: 98
    //   })
    // }
  })
}

const destroyCropper = () => {
  if (cropper.value) {
    cropper.value.destroy()
    cropper.value = null
  }
}

const cropImage = () => {
  if (!cropper.value) return

  const canvas = cropper.value.getCroppedCanvas({
    width: 116,
    height: 98,
    fillColor: '#000000',  // 使用白色背景更常见
    imageSmoothingEnabled: true,
    imageSmoothingQuality: 'high',
    minWidth: 116,       // 不限制最小宽度
    minHeight: 98,      // 不限制最小高度
    maxWidth: 116, // 不限制最大宽度
    maxHeight: 98 // 不限制最大高度
  })
   canvas.toBlob((blob) => {
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `cropped-${Date.now()}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }, 'image/png', 0.95)  // 提高图片质量
}

// 组件卸载时清理资源
onBeforeUnmount(() => {
  destroyCropper()
})
</script>
<style scoped>
.cropper-container {
  width: 116px;
  height: 98px;
  margin: 20px auto;
}



button {
  margin-top: 10px;
  padding: 8px 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
</style>
